package cn.tedu.egweibo5.controller;

import cn.tedu.egweibo5.base.response.JsonResult;
import cn.tedu.egweibo5.base.response.StatusCode;
import cn.tedu.egweibo5.mappers.UserMapper;
import cn.tedu.egweibo5.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo5.pojo.dto.UserRegDTO;
import cn.tedu.egweibo5.pojo.entity.User;
import cn.tedu.egweibo5.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

/**
 * @Author: Miyako
 * @CreateTime: 2024-08-14  20:20
 * @Description: TODO
 */
@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    UserMapper userMapper;
    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    JsonResult reg(@Validated @RequestBody UserRegDTO userRegDTO){
        log.debug("userRegDTO:"+userRegDTO);
        String username = userRegDTO.getUsername();
        UserVO userVO = userMapper.selectUserByUsername(username);
        if (userVO!=null){
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        userMapper.reg(user);
        return JsonResult.ok(null);

    }


    @ApiOperation("登录模块")
    @PostMapping("login")
    JsonResult login(@Validated @RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        UserVO userVO = userMapper.selectUserByUsername(userLoginDTO.getUsername());
            if (userVO==null){
               return new JsonResult(StatusCode.USERNAME_ERROR);//返回用户名错误
            }
            if (!(userVO.getPassword().equals(userLoginDTO.getPassword())))
                return new JsonResult(StatusCode.PASSWORD_ERROR);//返回密码错误
            session.setAttribute("user",userVO);//记录登录状态
        return JsonResult.ok(null);//操作成功
    }


    @ApiOperation("获取当前用户")
    @GetMapping("currentUser")
    JsonResult currentUser(@ApiIgnore HttpSession session ){
        UserVO user = (UserVO)session.getAttribute("user");
        return JsonResult.ok(user);
    }


    @ApiOperation("退出登录")
    @GetMapping("logout")
    void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");//删除登录信息
    }





}
